import 'package:aitao_flutter/common_ui/circle_avatar.dart';
import 'package:aitao_flutter/common_ui/online_status.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/style/text_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../common_ui/empty_view.dart';
import '../../model/relation_model.dart';
import '../../refresh/custom_refresh_footer.dart';
import '../../refresh/custom_refresh_header.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../routes/routes.dart';

class SeeMePage extends StatefulWidget {
  const SeeMePage({super.key});

  @override
  State<SeeMePage> createState() => _SeeMePageState();
}

class _SeeMePageState extends State<SeeMePage>
    with AutomaticKeepAliveClientMixin {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  final List<RelationModel> _list = [];
  int _page = 1;
  int _totalPage = 1;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _list.isEmpty
        ? EmptyView()
        : SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: _page < _totalPage,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            header: CustomClassicHeader(),
            footer: const CustomClassicFooter(),
            child: ListView.builder(
              itemBuilder: ((context, index) {
                return _userItem(index);
              }),
              itemCount: _list.length,
            ),
          );
  }

  Widget _userItem(int index) {
    RelationModel model = _list[index];
    return GestureDetector(child: Container(
      color: ColorStyle.whiteColor,
      padding: EdgeInsetsStyle.edgeInsets(16, 20),
      child: Row(children: [
        CircleAvatarWidget(url: model.avatar ?? '', gender: model.gender ?? 1),
        Box.hBox12,
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              model.nickname ?? '',
              style: Styles.normalText_15,
            ),
            Box.vBox(8),
            Row(
              children: [
                OnlineStatus(status: model.userState ?? 1),
                Box.hBox5,
                Text(model.dateline ?? '')
              ],
            )
          ],
        ),
        const Spacer(),
        _rightBtnWidget(model.isFollow == 1 ? '已关注' : '+关注'),
        Box.hBox15,
        _rightBtnWidget('私聊')
      ]),
    ),onTap: (){
      Get.toNamed(Routes.personalPage, parameters: {'userId': model.userid.toString()});
    },);
  }

  Widget _rightBtnWidget(String title) {
    return Container(
      padding: EdgeInsetsStyle.edgeInsets(15, 6),
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: RadiusStyle.radiusAll(6),
          gradient: ColorStyle.gravitationItemColor),
      child: Text(
        title,
        style: Styles.whiteText_11,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    loadNewList();
  }

  void loadNewList() async {
    var result =
        await RequestManager().post(API.visitorList, params: {'page': _page});
    if (result != null && result['code'] == 0) {
      _list.clear();
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      List tempList = result['data']['list'];
      for (var element in tempList) {
        RelationModel m = RelationModel.fromJson(element);
        _list.add(m);
      }
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(API.visitorList, params: {'type': 0, 'page': _page});
    if (result != null && result['code'] == 0) {
      _page = result['data']['page'];
      _totalPage = result['data']['total_page'];
      if (_page >= _totalPage) {
        _refreshController.loadNoData();
      }
      List tempList = result['data']['list'];
      _list.addAll(tempList.map((e) {
        RelationModel m = RelationModel.fromJson(e);
        return m;
      }));
      if (mounted) {
        setState(() {});
      }
    }
  }

  void _onRefresh() {
    _page = 1;
    _totalPage = 1;
    loadNewList();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _page += 1;
    loadMoreList();
    _refreshController.loadComplete();
  }
}
